/**
 * 文件同步器 - 主界面脚本
 */

// 避免重复加载和重复声明
if (typeof window.mainJsLoaded !== 'undefined' && window.mainJsLoaded === true) {
  console.warn('[Main] main.js 已经加载，跳过重复执行');
  // 已经加载过，不再继续执行
} else {
  window.mainJsLoaded = true;
  console.log('[Main] 开始加载 main.js...');

// 使用 window 对象避免重复声明
if (!window.mainJsModules) {
  window.mainJsModules = {
    ipcRenderer: require('electron').ipcRenderer,
    shell: require('electron').shell,
    path: require('path'),
    os: require('os')
  };
}

const { ipcRenderer, shell } = window.mainJsModules;
const path = window.mainJsModules.path;
const os = window.mainJsModules.os;

// ==================== 全局变量 ====================
let tasks = [];
let notifications = [];
let currentLocalPath = '';
let currentRemotePath = '/';
let isWindowsOS = process.platform === 'win32'; // 检测是否为 Windows 系统
const MY_COMPUTER = '__MY_COMPUTER__'; // 特殊标识：磁盘列表视图

// 过滤器状态
let currentTypeFilter = 'all'; // all, upload, download
let currentStatusFilter = 'all'; // all, active, completed, failed
let selectedLocalFiles = [];
let selectedRemoteFiles = [];

// 批量选择状态
let batchMode = false; // 是否处于批量选择模式
let selectedLocalItems = new Set(); // 选中的本地文件
let selectedRemoteItems = new Set(); // 选中的远程文件

// 性能优化：节流更新
let updateThrottleTimers = new Map(); // 每个任务的节流定时器
let pendingUpdates = new Map(); // 待更新的任务数据
const THROTTLE_DELAY = 200; // 节流延迟（毫秒）

// 队列统计更新节流
let queueStatsTimer = null;
const STATS_UPDATE_DELAY = 500; // 统计更新延迟（毫秒）

// 批量DOM更新
let rafId = null;
let batchUpdateQueue = new Set();

// 分页加载
const PAGE_SIZE = 500; // 每页显示的任务数
let currentPage = 1; // 当前页码
let isLoadingMore = false; // 是否正在加载更多

// ==================== DOM元素 ====================
// 延迟获取DOM元素，在初始化时获取
let serverStatus, serverStatusText, notificationBtn, notificationBadge;
let settingsBtn, logoutBtn, minimizeBtn, maximizeBtn;
let localPath, localUpBtn, localRefreshBtn, localHomeBtn, localFiles;
let remotePath, remoteUpBtn, remoteRefreshBtn, remoteHomeBtn, remoteFiles;
let transferList, queueStats, pauseAllBtn, resumeAllBtn, cancelAllBtn, clearCompletedBtn;
let notificationPanel, closeNotificationBtn, notificationList;
let markAllReadBtn, clearReadNotificationsBtn;
let settingsPanel, closeSettingsBtn, maxConcurrentInput, openLogBtn;

// 批量操作相关元素
let localSelectAll, remoteSelectAll;
let batchOperationPanel, batchCount, batchCancelBtn, batchUploadBtn, batchDownloadBtn;

// 获取DOM元素的函数
function getDOMElements() {
  serverStatus = document.getElementById('serverStatus');
  serverStatusText = document.getElementById('serverStatusText');
  notificationBtn = document.getElementById('notificationBtn');
  notificationBadge = document.getElementById('notificationBadge');
  settingsBtn = document.getElementById('settingsBtn');
  logoutBtn = document.getElementById('logoutBtn');
  minimizeBtn = document.getElementById('minimizeBtn');
  maximizeBtn = document.getElementById('maximizeBtn');

  localPath = document.getElementById('localPath');
  localUpBtn = document.getElementById('localUpBtn');
  localRefreshBtn = document.getElementById('localRefreshBtn');
  localHomeBtn = document.getElementById('localHomeBtn');
  localFiles = document.getElementById('localFiles');

  remotePath = document.getElementById('remotePath');
  remoteUpBtn = document.getElementById('remoteUpBtn');
  remoteRefreshBtn = document.getElementById('remoteRefreshBtn');
  remoteHomeBtn = document.getElementById('remoteHomeBtn');
  remoteFiles = document.getElementById('remoteFiles');

  transferList = document.getElementById('transferList');
  queueStats = document.getElementById('queueStats');
  pauseAllBtn = document.getElementById('pauseAllBtn');
  resumeAllBtn = document.getElementById('resumeAllBtn');
  cancelAllBtn = document.getElementById('cancelAllBtn');
  clearCompletedBtn = document.getElementById('clearCompletedBtn');

  notificationPanel = document.getElementById('notificationPanel');
  closeNotificationBtn = document.getElementById('closeNotificationBtn');
  notificationList = document.getElementById('notificationList');
  markAllReadBtn = document.getElementById('markAllReadBtn');
  clearReadNotificationsBtn = document.getElementById('clearReadNotificationsBtn');

  settingsPanel = document.getElementById('settingsPanel');
  closeSettingsBtn = document.getElementById('closeSettingsBtn');
  maxConcurrentInput = document.getElementById('maxConcurrentInput');
  openLogBtn = document.getElementById('openLogBtn');
  
  // 批量操作元素
  localSelectAll = document.getElementById('localSelectAll');
  remoteSelectAll = document.getElementById('remoteSelectAll');
  batchOperationPanel = document.getElementById('batchOperationPanel');
  batchCount = document.getElementById('batchCount');
  batchCancelBtn = document.getElementById('batchCancelBtn');
  batchUploadBtn = document.getElementById('batchUploadBtn');
  batchDownloadBtn = document.getElementById('batchDownloadBtn');
}

// ==================== 事件监听器设置 ====================
function setupEventListeners() {
  console.log('[Main] 绑定事件监听器...');
  
  // 窗口控制
  if (minimizeBtn) {
    minimizeBtn.addEventListener('click', () => {
      ipcRenderer.send('app-minimize');
    });
  }

  if (maximizeBtn) {
    maximizeBtn.addEventListener('click', () => {
      ipcRenderer.send('app-maximize');
    });
  }

  if (logoutBtn) {
    logoutBtn.addEventListener('click', async () => {
      if (confirm('确定要退出登录吗？')) {
        await ipcRenderer.invoke('logout');
      }
    });
  }
  
  // 选择本地目录按钮（允许切换磁盘）
  const chooseLocalDirBtn = document.getElementById('choose-local-dir-btn');
  if (chooseLocalDirBtn) {
    chooseLocalDirBtn.addEventListener('click', async () => {
      try {
        const selectedPath = await ipcRenderer.invoke('open-directory-dialog');
        if (selectedPath) {
          console.log('[Main] 用户选择了目录:', selectedPath);
          await loadLocalDirectory(selectedPath);
        }
      } catch (error) {
        console.error('[Main] 选择目录失败:', error);
        alert('选择目录失败: ' + error.message);
      }
    });
  }
  
  // 本地文件操作
  if (localUpBtn) {
    localUpBtn.addEventListener('click', () => {
      console.log('[Main] 返回上一级');
      
      // 如果当前在磁盘列表，无法再往上
      if (currentLocalPath === MY_COMPUTER) {
        console.log('[Main] 已经在顶级目录');
        return;
      }
      
      // Windows 系统：检查是否在磁盘根目录
      if (isWindowsOS) {
        // 判断是否为磁盘根目录 (如 C:\, D:\ 等)
        if (currentLocalPath.match(/^[A-Z]:\\?$/i)) {
          console.log('[Main] 在磁盘根目录，显示磁盘列表');
          loadLocalDirectory(MY_COMPUTER);
          return;
        }
      }
      
      const parentDir = path.dirname(currentLocalPath);
      if (parentDir !== currentLocalPath) {
        loadLocalDirectory(parentDir);
      } else if (isWindowsOS) {
        // 已经到达顶层，显示磁盘列表
        loadLocalDirectory(MY_COMPUTER);
      }
    });
  }

  if (localRefreshBtn) {
    localRefreshBtn.addEventListener('click', () => {
      loadLocalDirectory(currentLocalPath);
    });
  }

  if (localHomeBtn) {
    localHomeBtn.addEventListener('click', async () => {
      const homePath = await ipcRenderer.invoke('get-home-path');
      loadLocalDirectory(homePath);
    });
  }
  
  // 远程文件操作
  if (remoteUpBtn) {
    remoteUpBtn.addEventListener('click', async () => {
      const parentDir = path.posix.dirname(currentRemotePath);
      if (parentDir !== currentRemotePath) {
        await loadRemoteDirectory(parentDir);
      }
    });
  }

  if (remoteRefreshBtn) {
    remoteRefreshBtn.addEventListener('click', () => {
      console.log('🔄 用户点击刷新按钮');
      refreshRemoteDirectory();
    });
  }

  if (remoteHomeBtn) {
    remoteHomeBtn.addEventListener('click', () => {
      loadRemoteDirectory('/');
    });
  }
  
  // 队列操作
  if (pauseAllBtn) {
    pauseAllBtn.addEventListener('click', async () => {
      await ipcRenderer.invoke('pause-all-tasks');
    });
  }

  if (resumeAllBtn) {
    resumeAllBtn.addEventListener('click', async () => {
      await ipcRenderer.invoke('resume-all-tasks');
    });
  }

  if (cancelAllBtn) {
    cancelAllBtn.addEventListener('click', async () => {
      if (confirm('确定要取消所有传输任务吗？')) {
        await ipcRenderer.invoke('cancel-all-tasks');
      }
    });
  }

  if (clearCompletedBtn) {
    clearCompletedBtn.addEventListener('click', async () => {
      await ipcRenderer.invoke('clear-completed-tasks');
    });
  }

  // 滚动加载更多
  if (transferList) {
    transferList.addEventListener('scroll', () => {
      if (isLoadingMore) {
        return;
      }
      const scrollTop = transferList.scrollTop;
      const scrollHeight = transferList.scrollHeight;
      const clientHeight = transferList.clientHeight;
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadMoreTasks();
      }
    });
  }
  
  // 通知面板
  if (notificationBtn) {
    notificationBtn.addEventListener('click', () => {
      if (notificationPanel) {
        notificationPanel.classList.toggle('show');
      }
      if (settingsPanel) {
        settingsPanel.classList.remove('show');
      }
    });
  }

  if (closeNotificationBtn) {
    closeNotificationBtn.addEventListener('click', () => {
      if (notificationPanel) {
        notificationPanel.classList.remove('show');
      }
    });
  }

  if (markAllReadBtn) {
    markAllReadBtn.addEventListener('click', async () => {
      await ipcRenderer.invoke('mark-all-notifications-read');
      loadNotifications();
    });
  }

  if (clearReadNotificationsBtn) {
    clearReadNotificationsBtn.addEventListener('click', async () => {
      await ipcRenderer.invoke('clear-read-notifications');
      loadNotifications();
    });
  }
  
  // 设置面板
  if (settingsBtn) {
    settingsBtn.addEventListener('click', async () => {
      if (settingsPanel) {
        settingsPanel.classList.toggle('show');
      }
      if (notificationPanel) {
        notificationPanel.classList.remove('show');
      }
      if (settingsPanel && settingsPanel.classList.contains('show') && maxConcurrentInput) {
        try {
          const config = await ipcRenderer.invoke('get-config', 'transfer');
          if (config && config.maxConcurrent) {
            maxConcurrentInput.value = config.maxConcurrent;
          }
        } catch (error) {
          console.error('加载配置失败:', error);
        }
      }
    });
  }

  if (closeSettingsBtn) {
    closeSettingsBtn.addEventListener('click', () => {
      if (settingsPanel) {
        settingsPanel.classList.remove('show');
      }
    });
  }

  if (maxConcurrentInput) {
    maxConcurrentInput.addEventListener('change', async (e) => {
      const value = parseInt(e.target.value);
      if (value >= 1 && value <= 10) {
        await ipcRenderer.invoke('update-config', 'transfer', { maxConcurrent: value });
      }
    });
  }

  if (openLogBtn) {
    openLogBtn.addEventListener('click', async () => {
      const logPath = await ipcRenderer.invoke('get-log-path');
      shell.showItemInFolder(logPath);
    });
  }
  
  // 过滤器
  document.querySelectorAll('#typeFilter .filter-tab').forEach(tab => {
    tab.addEventListener('click', () => {
      document.querySelectorAll('#typeFilter .filter-tab').forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      currentTypeFilter = tab.dataset.type;
      filterTasks();
    });
  });

  document.querySelectorAll('#statusFilter .filter-tab').forEach(tab => {
    tab.addEventListener('click', () => {
      document.querySelectorAll('#statusFilter .filter-tab').forEach(t => t.classList.remove('active'));
      tab.classList.add('active');
      currentStatusFilter = tab.dataset.status;
      filterTasks();
    });
  });
  
  // 批量操作
  if (localSelectAll) {
    localSelectAll.addEventListener('change', (e) => {
      toggleSelectAllLocal(e.target.checked);
    });
  }
  
  if (remoteSelectAll) {
    remoteSelectAll.addEventListener('change', (e) => {
      toggleSelectAllRemote(e.target.checked);
    });
  }
  
  if (batchCancelBtn) {
    batchCancelBtn.addEventListener('click', () => {
      cancelBatchSelection();
    });
  }
  
  if (batchUploadBtn) {
    batchUploadBtn.addEventListener('click', () => {
      batchUploadFiles();
    });
  }
  
  if (batchDownloadBtn) {
    batchDownloadBtn.addEventListener('click', () => {
      batchDownloadFiles();
    });
  }
  
  console.log('[Main] 事件监听器绑定完成');
}

// ==================== 服务器状态 ====================
async function updateServerStatus() {
  try {
    const status = await ipcRenderer.invoke('get-server-status');
    if (serverStatus && serverStatusText) {
      if (status.connected && status.authenticated) {
        serverStatus.className = 'server-status online';
        serverStatusText.textContent = '在线';
      } else if (status.connected) {
        serverStatus.className = 'server-status connecting';
        serverStatusText.textContent = '连接中';
      } else {
        serverStatus.className = 'server-status offline';
        serverStatusText.textContent = '离线';
      }
    }
  } catch (error) {
    if (serverStatus && serverStatusText) {
      serverStatus.className = 'server-status offline';
      serverStatusText.textContent = '错误';
    }
  }
}

// 监听WebSocket状态变化
ipcRenderer.on('ws-connected', () => {
  if (serverStatus && serverStatusText) {
    serverStatus.className = 'server-status online';
    serverStatusText.textContent = '在线';
  }
});

ipcRenderer.on('ws-disconnected', () => {
  if (serverStatus && serverStatusText) {
    serverStatus.className = 'server-status offline';
    serverStatusText.textContent = '离线';
  }
});

ipcRenderer.on('ws-reconnecting', (event, attempt) => {
  if (serverStatus && serverStatusText) {
    serverStatus.className = 'server-status connecting';
    serverStatusText.textContent = `重连中 (${attempt})`;
  }
});

// ==================== 本地文件浏览 ====================
async function loadLocalDirectory(dirPath, clearSelection = true) {
  try {
    // 特殊处理：显示磁盘列表
    if (dirPath === MY_COMPUTER) {
      showDrivesList(clearSelection);
      return;
    }
    
    const files = await ipcRenderer.invoke('read-directory', dirPath);
    currentLocalPath = dirPath;
    localPath.value = dirPath;
    
    // 清除选择状态（可选）
    if (clearSelection) {
      selectedLocalItems.clear();
      if (localSelectAll) localSelectAll.checked = false;
    }
    
    localFiles.innerHTML = '';
    
    // 排序：文件夹在前，文件在后
    files.sort((a, b) => {
      if (a.isDirectory === b.isDirectory) {
        return a.name.localeCompare(b.name);
      }
      return a.isDirectory ? -1 : 1;
    });
    
    files.forEach(file => {
      const item = createFileItem(file, 'local');
      localFiles.appendChild(item);
      
      // 如果文件在选中列表中，恢复选中状态
      if (!clearSelection) {
        const fileData = JSON.stringify({
          path: file.path,
          name: file.name,
          id: file.id,
          isDirectory: file.isDirectory,
          size: file.size || 0
        });
        if (selectedLocalItems.has(fileData)) {
          const checkbox = item.querySelector('input[type="checkbox"]');
          if (checkbox) {
            checkbox.checked = true;
            item.classList.add('selected');
          }
        }
      }
    });
    
    updateBatchOperationPanel();
  } catch (error) {
    console.error('加载本地目录失败:', error);
    alert('加载本地目录失败: ' + error.message);
  }
}

// 显示磁盘列表（Windows）
async function showDrivesList(clearSelection = true) {
  console.log('显示磁盘列表');
  currentLocalPath = MY_COMPUTER;
  localPath.value = '💻 此电脑';
  
  // 清除选择状态
  if (clearSelection) {
    selectedLocalItems.clear();
    if (localSelectAll) localSelectAll.checked = false;
  }
  
  localFiles.innerHTML = '<div class="empty-state">⏳ 正在检测磁盘...</div>';
  
  try {
    // 从主进程获取实际可用的磁盘列表
    const drives = await ipcRenderer.invoke('get-available-drives');
    
    console.log('检测到的可用磁盘:', drives);
    
    localFiles.innerHTML = '';
    
    if (!drives || drives.length === 0) {
      localFiles.innerHTML = '<div class="empty-state">未检测到可用磁盘</div>';
      updateBatchOperationPanel();
      return;
    }
    
    drives.forEach(drive => {
      const driveItem = {
        name: `本地磁盘 (${drive})`,
        path: drive + '\\',
        isDirectory: true,
        size: 0,
        modifiedTime: new Date(),
        isDrive: true,
        drive: drive
      };
      
      const item = createDriveItem(driveItem);
      localFiles.appendChild(item);
    });
    
    updateBatchOperationPanel();
  } catch (error) {
    console.error('获取磁盘列表失败:', error);
    localFiles.innerHTML = '<div class="empty-state">获取磁盘列表失败</div>';
    updateBatchOperationPanel();
  }
}

// 创建磁盘项（样式和文件夹完全一样）
function createDriveItem(driveInfo) {
  const item = document.createElement('div');
  item.className = 'file-item';
  
  item.dataset.path = driveInfo.path;
  item.dataset.name = driveInfo.name;
  item.dataset.isDirectory = 'true';
  item.dataset.size = 0;
  item.dataset.type = 'local';
  
  // 添加复选框（可选，保持和文件夹一致）
  const checkboxSpan = document.createElement('span');
  checkboxSpan.className = 'file-item-checkbox';
  const checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.onclick = (e) => {
    e.stopPropagation();
    // 磁盘项不支持选择操作，可以禁用
    checkbox.checked = false;
  };
  checkboxSpan.appendChild(checkbox);
  
  // 使用文件夹图标（和普通文件夹一样）
  const icon = document.createElement('span');
  icon.className = 'file-icon';
  icon.innerHTML = '<img src="./assets/Folder.svg" alt="文件夹" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
  
  const name = document.createElement('span');
  name.className = 'file-item-name';
  name.textContent = driveInfo.name;
  
  const size = document.createElement('span');
  size.className = 'file-item-size';
  size.textContent = '-';
  
  const date = document.createElement('span');
  date.className = 'file-item-date';
  date.textContent = '-';
  
  const actions = document.createElement('span');
  actions.className = 'file-item-actions';
  // 不添加任何按钮，和文件夹一样
  
  item.appendChild(checkboxSpan);
  item.appendChild(icon);
  item.appendChild(name);
  item.appendChild(size);
  item.appendChild(date);
  item.appendChild(actions);
  
  // 双击打开磁盘（和文件夹一样的操作）
  item.ondblclick = () => {
    console.log('打开磁盘:', driveInfo.drive);
    loadLocalDirectory(driveInfo.path);
  };
  
  return item;
}

// ==================== 远程文件浏览 ====================
async function loadRemoteDirectory(dirPath, clearSelection = true) {
  try {
    console.log(`📂 加载远程目录: ${dirPath}`);
    const result = await ipcRenderer.invoke('remote-list', dirPath);
    console.log('远程文件列表结果:', result);
    
    if (!result.success) {
      throw new Error(result.message);
    }
    
    const files = result.data;
    console.log(`✅ 获取到 ${files.length} 个文件/文件夹`);
    console.log('文件详情:', files.map(f => ({ 
      name: f.file_name || f.name, 
      path: f.file_path || f.path,
      isDir: f.is_directory || f.isDirectory 
    })));
    
    currentRemotePath = dirPath;
    remotePath.value = dirPath;
    
    // 清除选择状态（可选）
    if (clearSelection) {
      selectedRemoteItems.clear();
      if (remoteSelectAll) remoteSelectAll.checked = false;
    }
    
    remoteFiles.innerHTML = '';
    
    // 排序：文件夹在前，文件在后
    files.sort((a, b) => {
      const aIsDir = a.is_directory || a.isDirectory;
      const bIsDir = b.is_directory || b.isDirectory;
      
      if (aIsDir === bIsDir) {
        return (a.file_name || a.name).localeCompare(b.file_name || b.name);
      }
      return aIsDir ? -1 : 1;
    });
    
    files.forEach(file => {
      const item = createFileItem(file, 'remote');
      remoteFiles.appendChild(item);
      
      // 如果文件在选中列表中，恢复选中状态
      if (!clearSelection) {
        const fileData = JSON.stringify({
          path: file.file_path || file.path,
          name: file.file_name || file.name,
          id: file.file_id || file.id,
          isDirectory: file.is_directory || file.isDirectory,
          size: file.file_size || file.size || 0
        });
        if (selectedRemoteItems.has(fileData)) {
          const checkbox = item.querySelector('input[type="checkbox"]');
          if (checkbox) {
            checkbox.checked = true;
            item.classList.add('selected');
          }
        }
      }
    });
    
    updateBatchOperationPanel();
  } catch (error) {
    console.error('加载远程目录失败:', error);
    alert('加载远程目录失败: ' + error.message);
  }
}

// 刷新远程目录（防抖）
let refreshRemoteTimer = null;
function refreshRemoteDirectory() {
  // 防抖：避免频繁刷新
  if (refreshRemoteTimer) {
    clearTimeout(refreshRemoteTimer);
  }
  
  refreshRemoteTimer = setTimeout(async () => {
    if (currentRemotePath) {
      console.log('🔄 刷新远程目录:', currentRemotePath);
      await loadRemoteDirectory(currentRemotePath, false);
    }
    refreshRemoteTimer = null;
  }, 500); // 500ms防抖
}

// ==================== 文件项创建 ====================
function createFileItem(file, type) {
  const item = document.createElement('div');
  item.className = 'file-item';
  
  // 兼容本地和远程文件的数据格式
  const fileName = file.file_name || file.name;
  const fileSize = file.file_size || file.size;
  const isDirectory = file.is_directory || file.isDirectory;
  const filePath = file.file_path || file.path;
  const fileId = file.id; // 远程文件有ID
  const modified = file.updated_at || file.modified;
  
  item.dataset.path = filePath;
  item.dataset.name = fileName;
  item.dataset.isDirectory = isDirectory;
  item.dataset.size = fileSize;
  item.dataset.type = type;
  if (fileId) item.dataset.fileId = fileId;
  
  // 添加复选框
  const checkboxSpan = document.createElement('span');
  checkboxSpan.className = 'file-item-checkbox';
  const checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.onclick = (e) => {
    e.stopPropagation();
    handleFileCheckboxChange(item, type, checkbox.checked);
  };
  checkboxSpan.appendChild(checkbox);
  
  const icon = document.createElement('span');
  icon.className = 'file-icon';
  if (isDirectory) {
    icon.innerHTML = '<img src="./assets/Folder.svg" alt="文件夹" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
  } else {
    // 检查文件类型
    const ext = fileName.split('.').pop().toLowerCase();
    
    // 图片文件
    const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tif', 'tiff'];
    if (imageExts.includes(ext)) {
      icon.innerHTML = '<img src="./assets/Photo.svg" alt="图片文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
    }
    // 视频文件
    else {
      const videoExts = ['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', 'm4v', 'mpg', 'mpeg'];
      if (videoExts.includes(ext)) {
        icon.innerHTML = '<img src="./assets/Video.svg" alt="视频文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
      }
      // 链接文件
      else {
        const linkExts = ['url', 'lnk', 'link', 'webloc', 'desktop'];
        if (linkExts.includes(ext)) {
          icon.innerHTML = '<img src="./assets/Url.svg" alt="链接文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
        }
        // 音乐文件
        else {
          const musicExts = ['mp3', 'wav', 'flac', 'aac', 'm4a', 'ogg', 'wma', 'ape', 'alac'];
          if (musicExts.includes(ext)) {
            icon.innerHTML = '<img src="./assets/Music.svg" alt="音乐文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
          }
          // 表格文件
          else {
            const spreadsheetExts = ['xls', 'xlsx', 'xlsm', 'csv', 'ods'];
            if (spreadsheetExts.includes(ext)) {
              icon.innerHTML = '<img src="./assets/Xls.svg" alt="表格文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
            }
            // Word文档
            else {
              const wordExts = ['doc', 'docx', 'docm', 'dot', 'dotx', 'odt'];
              if (wordExts.includes(ext)) {
                icon.innerHTML = '<img src="./assets/Word.svg" alt="Word文档" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
              }
              // 文本文件
              else {
                const textExts = ['txt', 'text', 'log'];
                if (textExts.includes(ext)) {
                  icon.innerHTML = '<img src="./assets/Txt.svg" alt="文本文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                }
                // 压缩文件
                else {
                  const archiveExts = ['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'iso'];
                  if (archiveExts.includes(ext)) {
                    icon.innerHTML = '<img src="./assets/Zip.svg" alt="压缩文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                  }
                  // 代码文件
                  else {
                    const codeExts = ['js', 'jsx', 'ts', 'tsx', 'py', 'java', 'c', 'cpp', 'h', 'hpp', 'cs', 'php', 'rb', 'go', 'rs', 'swift', 'kt', 'vue', 'html', 'css', 'scss', 'sass', 'less', 'json', 'xml', 'yaml', 'yml', 'sh', 'bash', 'md', 'markdown'];
                    if (codeExts.includes(ext)) {
                      icon.innerHTML = '<img src="./assets/Dm.svg" alt="代码文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                    }
                    // 配置文件
                    else {
                      const configExts = ['ini', 'conf', 'config', 'cfg', 'properties', 'env', 'toml', 'editorconfig', 'npmrc', 'gitignore'];
                      if (configExts.includes(ext)) {
                        icon.innerHTML = '<img src="./assets/Pz.svg" alt="配置文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                      }
                      // PDF文件
                      else if (ext === 'pdf') {
                        icon.innerHTML = '<img src="./assets/PDF.svg" alt="PDF文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                      }
                      // PPT文件
                      else {
                        const pptExts = ['ppt', 'pptx', 'pptm', 'potx', 'ppsx'];
                        if (pptExts.includes(ext)) {
                          icon.innerHTML = '<img src="./assets/PPT.svg" alt="PPT文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                        }
                        // 3D模型文件
                        else {
                          const modelExts = ['obj', 'fbx', '3ds', 'stl', 'dae', 'gltf', 'glb', 'blend', 'max', 'c4d', 'ma', 'mb'];
                          if (modelExts.includes(ext)) {
                            icon.innerHTML = '<img src="./assets/3D.svg" alt="3D模型" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                          }
                          // 数据库文件
                          else {
                            const dbExts = ['sql', 'db', 'sqlite', 'sqlite3', 'mdb', 'accdb', 'dbf', 'sdf'];
                            if (dbExts.includes(ext)) {
                              icon.innerHTML = '<img src="./assets/sql.svg" alt="数据库文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                            } else {
                              icon.innerHTML = '<img src="./assets/404.svg" alt="未知文件" style="width: 20.16px; height: 20.16px; vertical-align: middle;">';
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  
  const name = document.createElement('span');
  name.className = 'file-name';
  name.textContent = fileName;
  
  const size = document.createElement('span');
  size.className = 'file-size';
  size.textContent = isDirectory ? '-' : formatFileSize(fileSize || 0);
  
  const modifiedSpan = document.createElement('span');
  modifiedSpan.className = 'file-modified';
  modifiedSpan.textContent = modified ? new Date(modified).toLocaleString() : '-';
  
  const actions = document.createElement('span');
  actions.className = 'file-actions';
  
  if (type === 'local' && !isDirectory) {
    const uploadBtn = document.createElement('button');
    uploadBtn.className = 'btn-action';
    uploadBtn.textContent = '↑ 上传';
    uploadBtn.onclick = (e) => {
      e.stopPropagation();
      uploadFile(filePath);
    };
    actions.appendChild(uploadBtn);
  } else if (type === 'local' && isDirectory) {
    const uploadFolderBtn = document.createElement('button');
    uploadFolderBtn.className = 'btn-action';
    uploadFolderBtn.textContent = '↑ 上传文件夹';
    uploadFolderBtn.onclick = (e) => {
      e.stopPropagation();
      uploadFolder(filePath, fileName);
    };
    actions.appendChild(uploadFolderBtn);
  } else if (type === 'remote' && !isDirectory) {
    const downloadBtn = document.createElement('button');
    downloadBtn.className = 'btn-action';
    downloadBtn.textContent = '↓ 下载';
    downloadBtn.onclick = (e) => {
      e.stopPropagation();
      downloadFile(fileId, fileName, fileSize);
    };
    actions.appendChild(downloadBtn);
  }
  
  item.appendChild(checkboxSpan);
  item.appendChild(icon);
  item.appendChild(name);
  item.appendChild(size);
  item.appendChild(modifiedSpan);
  item.appendChild(actions);
  
  // 双击事件
  if (isDirectory) {
    item.ondblclick = () => {
      console.log(`双击文件夹: ${fileName}, 路径: ${filePath}, 类型: ${type}`);
      if (type === 'local') {
        loadLocalDirectory(filePath);
      } else {
        console.log(`正在导航到远程目录: ${filePath}`);
        loadRemoteDirectory(filePath);
      }
    };
  }
  
  return item;
}

// ==================== 批量选择功能 ====================
function handleFileCheckboxChange(item, type, checked) {
  const filePath = item.dataset.path;
  const fileName = item.dataset.name;
  const fileId = item.dataset.fileId;
  const isDirectory = item.dataset.isDirectory === 'true';
  
  if (checked) {
    item.classList.add('selected');
    const fileData = {
      path: filePath,
      name: fileName,
      id: fileId,
      isDirectory: isDirectory,
      size: parseInt(item.dataset.size) || 0
    };
    
    if (type === 'local') {
      selectedLocalItems.add(JSON.stringify(fileData));
    } else {
      selectedRemoteItems.add(JSON.stringify(fileData));
    }
  } else {
    item.classList.remove('selected');
    const fileData = {
      path: filePath,
      name: fileName,
      id: fileId,
      isDirectory: isDirectory,
      size: parseInt(item.dataset.size) || 0
    };
    
    if (type === 'local') {
      selectedLocalItems.delete(JSON.stringify(fileData));
    } else {
      selectedRemoteItems.delete(JSON.stringify(fileData));
    }
  }
  
  updateBatchOperationPanel();
}

function toggleSelectAllLocal(checked) {
  const fileItems = localFiles.querySelectorAll('.file-item');
  fileItems.forEach(item => {
    const checkbox = item.querySelector('input[type="checkbox"]');
    if (checkbox) {
      checkbox.checked = checked;
      handleFileCheckboxChange(item, 'local', checked);
    }
  });
}

function toggleSelectAllRemote(checked) {
  const fileItems = remoteFiles.querySelectorAll('.file-item');
  fileItems.forEach(item => {
    const checkbox = item.querySelector('input[type="checkbox"]');
    if (checkbox) {
      checkbox.checked = checked;
      handleFileCheckboxChange(item, 'remote', checked);
    }
  });
}

function updateBatchOperationPanel() {
  const localCount = selectedLocalItems.size;
  const remoteCount = selectedRemoteItems.size;
  const totalCount = localCount + remoteCount;
  
  // 更新复选框的禁用状态
  if (localCount > 0) {
    // 已选择本地文件，禁用远程文件选择
    disableRemoteCheckboxes();
    enableLocalCheckboxes();
  } else if (remoteCount > 0) {
    // 已选择远程文件，禁用本地文件选择
    disableLocalCheckboxes();
    enableRemoteCheckboxes();
  } else {
    // 没有选择，全部启用
    enableLocalCheckboxes();
    enableRemoteCheckboxes();
  }
  
  if (totalCount > 0) {
    batchOperationPanel.style.display = 'flex';
    batchCount.textContent = `已选择 ${totalCount} 个文件`;
    
    // 显示对应的按钮
    if (localCount > 0 && remoteCount === 0) {
      batchUploadBtn.style.display = 'inline-block';
      batchDownloadBtn.style.display = 'none';
    } else if (remoteCount > 0 && localCount === 0) {
      batchUploadBtn.style.display = 'none';
      batchDownloadBtn.style.display = 'inline-block';
    } else if (localCount > 0 && remoteCount > 0) {
      // 两边都有选择，隐藏操作按钮
      batchUploadBtn.style.display = 'none';
      batchDownloadBtn.style.display = 'none';
    }
  } else {
    batchOperationPanel.style.display = 'none';
  }
}

// 禁用本地文件复选框
function disableLocalCheckboxes() {
  if (localSelectAll) localSelectAll.disabled = true;
  const localFileItems = localFiles.querySelectorAll('.file-item');
  localFileItems.forEach(item => {
    if (!item.classList.contains('selected')) {
      const checkbox = item.querySelector('input[type="checkbox"]');
      if (checkbox) checkbox.disabled = true;
    }
  });
}

// 启用本地文件复选框
function enableLocalCheckboxes() {
  if (localSelectAll) localSelectAll.disabled = false;
  const localFileItems = localFiles.querySelectorAll('.file-item');
  localFileItems.forEach(item => {
    const checkbox = item.querySelector('input[type="checkbox"]');
    if (checkbox) checkbox.disabled = false;
  });
}

// 禁用远程文件复选框
function disableRemoteCheckboxes() {
  if (remoteSelectAll) remoteSelectAll.disabled = true;
  const remoteFileItems = remoteFiles.querySelectorAll('.file-item');
  remoteFileItems.forEach(item => {
    if (!item.classList.contains('selected')) {
      const checkbox = item.querySelector('input[type="checkbox"]');
      if (checkbox) checkbox.disabled = true;
    }
  });
}

// 启用远程文件复选框
function enableRemoteCheckboxes() {
  if (remoteSelectAll) remoteSelectAll.disabled = false;
  const remoteFileItems = remoteFiles.querySelectorAll('.file-item');
  remoteFileItems.forEach(item => {
    const checkbox = item.querySelector('input[type="checkbox"]');
    if (checkbox) checkbox.disabled = false;
  });
}

function cancelBatchSelection() {
  // 清除本地选择
  selectedLocalItems.clear();
  if (localSelectAll) localSelectAll.checked = false;
  const localFileItems = localFiles.querySelectorAll('.file-item');
  localFileItems.forEach(item => {
    item.classList.remove('selected');
    const checkbox = item.querySelector('input[type="checkbox"]');
    if (checkbox) checkbox.checked = false;
  });
  
  // 清除远程选择
  selectedRemoteItems.clear();
  if (remoteSelectAll) remoteSelectAll.checked = false;
  const remoteFileItems = remoteFiles.querySelectorAll('.file-item');
  remoteFileItems.forEach(item => {
    item.classList.remove('selected');
    const checkbox = item.querySelector('input[type="checkbox"]');
    if (checkbox) checkbox.checked = false;
  });
  
  updateBatchOperationPanel();
}

async function batchUploadFiles() {
  if (selectedLocalItems.size === 0) return;
  
  const files = Array.from(selectedLocalItems).map(str => JSON.parse(str));
  const fileCount = files.filter(f => !f.isDirectory).length;
  const folderCount = files.filter(f => f.isDirectory).length;
  
  const confirmMsg = `确定要上传 ${fileCount} 个文件${folderCount > 0 ? ` 和 ${folderCount} 个文件夹` : ''}吗？`;
  if (!confirm(confirmMsg)) return;
  
  console.log(`[批量上传] 开始上传 ${files.length} 个项目`);
  
  for (const file of files) {
    try {
      if (file.isDirectory) {
        await uploadFolder(file.path, file.name);
      } else {
        await uploadFile(file.path);
      }
    } catch (error) {
      console.error(`上传失败: ${file.name}`, error);
    }
  }
  
  console.log(`[批量上传] 完成`);
  cancelBatchSelection();
}

async function batchDownloadFiles() {
  if (selectedRemoteItems.size === 0) return;
  
  const files = Array.from(selectedRemoteItems).map(str => JSON.parse(str));
  const fileCount = files.filter(f => !f.isDirectory).length;
  
  if (fileCount === 0) {
    alert('请选择要下载的文件（不支持下载文件夹）');
    return;
  }
  
  const confirmMsg = `确定要下载 ${fileCount} 个文件吗？`;
  if (!confirm(confirmMsg)) return;
  
  console.log(`[批量下载] 开始下载 ${fileCount} 个文件`);
  
  for (const file of files) {
    if (!file.isDirectory) {
      try {
        await downloadFile(file.id, file.name, file.size);
      } catch (error) {
        console.error(`下载失败: ${file.name}`, error);
      }
    }
  }
  
  console.log(`[批量下载] 完成`);
  cancelBatchSelection();
}

// ==================== 文件传输 ====================
async function uploadFile(localPath) {
  const fileName = path.basename(localPath);
  // 智能上传：上传到当前远程目录
  const remotePath = path.posix.join(currentRemotePath, fileName);
  
  console.log(`智能上传 - 本地文件: ${localPath}`);
  console.log(`智能上传 - 目标路径: ${remotePath} (当前远程目录: ${currentRemotePath})`);
  
  try {
    const fileInfo = await ipcRenderer.invoke('get-file-info', localPath);
    
    // 检查远程文件是否存在
    const remoteList = await ipcRenderer.invoke('remote-list', currentRemotePath);
    const existingFile = remoteList.data?.find(f => {
      const fileName = f.file_name || f.name;
      const fileSize = f.file_size || f.size;
      return fileName === path.basename(localPath) && fileSize === fileInfo.size;
    });
    
    if (existingFile) {
      // 文件名和大小相同，跳过
      console.log('文件已存在且大小相同，跳过上传:', fileName);
      return;
    }
    
    // 添加上传任务到当前远程目录
    await ipcRenderer.invoke('add-upload-task', localPath, remotePath);
    console.log(`✓ 上传任务已添加: ${fileName} -> ${currentRemotePath}/`);
  } catch (error) {
    console.error('添加上传任务失败:', error);
    alert('上传失败: ' + error.message);
  }
}

async function downloadFile(fileId, fileName, fileSize) {
  try {
    // 智能下载：下载到当前本地目录
    let savePath;
    
    if (currentLocalPath) {
      // 如果本地有打开目录，直接下载到该目录
      savePath = path.join(currentLocalPath, fileName);
      console.log(`智能下载 - 远程文件ID: ${fileId}`);
      console.log(`智能下载 - 目标路径: ${savePath} (当前本地目录: ${currentLocalPath})`);
    } else {
      // 如果本地没有打开目录，下载到默认下载文件夹
      const downloadsPath = await ipcRenderer.invoke('get-downloads-path');
      savePath = path.join(downloadsPath, fileName);
      console.log(`智能下载 - 下载到默认目录: ${savePath}`);
    }
    
    // 检查文件是否已存在
    const fs = require('fs');
    if (fs.existsSync(savePath)) {
      const overwrite = confirm(`文件"${fileName}"已存在，是否覆盖？`);
      if (!overwrite) {
        return;
      }
    }
    
    // 添加下载任务（使用文件ID）
    await ipcRenderer.invoke('add-download-task', fileId, fileName, fileSize, savePath);
    console.log(`✓ 下载任务已添加: ${fileName} -> ${currentLocalPath || '默认下载目录'}/`);
  } catch (error) {
    console.error('添加下载任务失败:', error);
    alert('下载失败: ' + error.message);
  }
}

// 上传文件夹
async function uploadFolder(localFolderPath, folderName) {
  try {
    // 智能上传：上传到当前远程目录
    const remoteFolderPath = path.posix.join(currentRemotePath, folderName);
    
    console.log(`智能上传文件夹 - 本地路径: ${localFolderPath}`);
    console.log(`智能上传文件夹 - 目标路径: ${remoteFolderPath} (当前远程目录: ${currentRemotePath})`);
    
    const result = await ipcRenderer.invoke('upload-folder', localFolderPath, remoteFolderPath);
    
    if (result.success) {
      const { taskIds, totalFiles, folderName: uploadedFolder } = result.data;
      
      console.log(`✓ 文件夹"${uploadedFolder}"已添加到上传队列`);
      console.log(`  上传位置: ${currentRemotePath}/`);
      console.log(`  共 ${totalFiles} 个文件`);
      console.log(`  任务ID: ${taskIds.length > 5 ? taskIds.slice(0, 5).join(', ') + '...' : taskIds.join(', ')}`);
      
      // 切换到传输队列标签页（如果有的话）
      const transferTab = document.querySelector('[data-tab="transfer"]');
      if (transferTab) {
        transferTab.click();
      }
    } else {
      throw new Error(result.message);
    }
  } catch (error) {
    console.error('上传文件夹失败:', error);
    alert('上传文件夹失败: ' + error.message);
  }
}

// 显示文件夹上传进度
function showFolderUploadProgress(folderName) {
  const progressDiv = document.createElement('div');
  progressDiv.id = 'folder-upload-progress';
  progressDiv.style.cssText = `
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    z-index: 10000;
    min-width: 300px;
  `;
  
  progressDiv.innerHTML = `
    <h3 style="margin-top: 0;">正在上传文件夹: ${folderName}</h3>
    <div id="folder-current-file" style="margin: 10px 0;">准备中...</div>
    <div style="background: #e0e0e0; height: 20px; border-radius: 10px; overflow: hidden; margin: 10px 0;">
      <div id="folder-progress-bar" style="background: #4CAF50; height: 100%; width: 0%; transition: width 0.3s;"></div>
    </div>
    <div id="folder-progress-text" style="text-align: center;">0%</div>
    <div id="folder-file-count" style="margin-top: 10px; text-align: center;">0 / 0 文件</div>
  `;
  
  document.body.appendChild(progressDiv);
}

// 隐藏文件夹上传进度
function hideFolderUploadProgress() {
  const progressDiv = document.getElementById('folder-upload-progress');
  if (progressDiv) {
    progressDiv.remove();
  }
}

// 监听文件夹上传进度
ipcRenderer.on('folder-upload-progress', (event, progress) => {
  const progressBar = document.getElementById('folder-progress-bar');
  const progressText = document.getElementById('folder-progress-text');
  const currentFile = document.getElementById('folder-current-file');
  const fileCount = document.getElementById('folder-file-count');
  
  if (progressBar) {
    progressBar.style.width = `${progress.totalProgress}%`;
  }
  
  if (progressText) {
    progressText.textContent = `${Math.round(progress.totalProgress)}%`;
  }
  
  if (currentFile) {
    currentFile.textContent = `当前文件: ${progress.currentFile}`;
  }
  
  if (fileCount) {
    fileCount.textContent = `${progress.uploadedFiles} / ${progress.totalFiles} 文件`;
  }
});

// ==================== 传输队列管理 ====================
async function loadTasks() {
  tasks = await ipcRenderer.invoke('get-tasks');
  renderTransferList();
  updateQueueStats();
}

function renderTransferList(append = false) {
  // 如果不是追加模式，重置页码和清空列表
  if (!append) {
    currentPage = 1;
    transferList.innerHTML = '';
  }
  
  // 应用过滤器
  let filteredTasks = tasks.filter(task => {
    // 类型过滤
    if (currentTypeFilter !== 'all' && task.type !== currentTypeFilter) {
      return false;
    }
    
    // 状态过滤
    if (currentStatusFilter !== 'all') {
      if (currentStatusFilter === 'active' && task.status !== 'active' && task.status !== 'pending') {
        return false;
      }
      if (currentStatusFilter === 'completed' && task.status !== 'completed') {
        return false;
      }
      if (currentStatusFilter === 'failed' && task.status !== 'failed') {
        return false;
      }
    }
    
    return true;
  });
  
  // 按时间倒序排列（最新的在最上面）
  filteredTasks.sort((a, b) => {
    // 假设任务有createdAt或id字段，id越大越新
    return (b.id || 0) - (a.id || 0);
  });
  
  if (filteredTasks.length === 0 && !append) {
    const message = tasks.length === 0 ? '暂无传输任务' : '没有符合条件的任务';
    transferList.innerHTML = `<div class="empty-state"><div class="empty-state-icon">📭</div><div>${message}</div></div>`;
    return;
  }
  
  // 分页：计算当前页要显示的任务
  const startIndex = (currentPage - 1) * PAGE_SIZE;
  const endIndex = startIndex + PAGE_SIZE;
  const tasksToRender = filteredTasks.slice(startIndex, endIndex);
  
  if (tasksToRender.length === 0) {
    isLoadingMore = false;
    return;
  }
  
  // 性能优化：使用DocumentFragment批量添加DOM
  const fragment = document.createDocumentFragment();
  tasksToRender.forEach(task => {
    const taskEl = createTaskElement(task);
    fragment.appendChild(taskEl);
  });
  transferList.appendChild(fragment);
  
  // 添加"加载更多"提示（如果还有更多任务）
  const loadMoreIndicator = document.getElementById('loadMoreIndicator');
  if (loadMoreIndicator) {
    loadMoreIndicator.remove();
  }
  
  if (endIndex < filteredTasks.length) {
    const indicator = document.createElement('div');
    indicator.id = 'loadMoreIndicator';
    indicator.className = 'load-more-indicator';
    indicator.textContent = `还有 ${filteredTasks.length - endIndex} 个任务，向下滚动加载更多...`;
    transferList.appendChild(indicator);
  }
  
  isLoadingMore = false;
}

function createTaskElement(task) {
  const el = document.createElement('div');
  el.className = 'transfer-task';
  el.dataset.taskId = task.id;
  el.dataset.status = task.status;
  
  const header = document.createElement('div');
  header.className = 'task-header';
  
  const typeIcon = task.type === 'upload' ? '↑' : '↓';
  const name = document.createElement('div');
  name.className = 'task-name';
  name.textContent = `${typeIcon} ${task.fileName}`;
  
  const actions = document.createElement('div');
  actions.className = 'task-actions';
  
  if (task.status === 'active') {
    const pauseBtn = document.createElement('button');
    pauseBtn.className = 'task-btn';
    pauseBtn.textContent = '⏸️ 暂停';
    pauseBtn.onclick = () => pauseTask(task.id);
    actions.appendChild(pauseBtn);
  } else if (task.status === 'paused') {
    const resumeBtn = document.createElement('button');
    resumeBtn.className = 'task-btn';
    resumeBtn.textContent = '▶️ 继续';
    resumeBtn.onclick = () => resumeTask(task.id);
    actions.appendChild(resumeBtn);
  } else if (task.status === 'failed') {
    const retryBtn = document.createElement('button');
    retryBtn.className = 'task-btn';
    retryBtn.textContent = '🔄 重试';
    retryBtn.onclick = () => retryTask(task.id);
    actions.appendChild(retryBtn);
  }
  
  if (task.status !== 'completed') {
    const cancelBtn = document.createElement('button');
    cancelBtn.className = 'task-btn';
    cancelBtn.textContent = '✕ 取消';
    cancelBtn.onclick = () => cancelTask(task.id);
    actions.appendChild(cancelBtn);
  }
  
  header.appendChild(name);
  header.appendChild(actions);
  
  const progress = document.createElement('div');
  progress.className = 'task-progress';
  
  const progressBar = document.createElement('div');
  progressBar.className = 'progress-bar';
  
  const progressFill = document.createElement('div');
  progressFill.className = `progress-fill ${task.status}`;
  progressFill.style.width = task.progress + '%';
  
  progressBar.appendChild(progressFill);
  progress.appendChild(progressBar);
  
  const info = document.createElement('div');
  info.className = 'task-info';
  
  const transferred = document.createElement('span');
  transferred.textContent = `${formatFileSize(task.transferred)} / ${formatFileSize(task.fileSize)}`;
  
  const speed = document.createElement('span');
  speed.className = 'task-speed';
  speed.textContent = task.speed > 0 ? formatSpeed(task.speed) : '-';
  
  const status = document.createElement('span');
  status.textContent = getStatusText(task.status);
  
  info.appendChild(transferred);
  info.appendChild(speed);
  info.appendChild(status);
  
  el.appendChild(header);
  el.appendChild(progress);
  el.appendChild(info);
  
  // 只有当任务状态为 failed 时才显示错误信息
  if (task.error && task.status === 'failed') {
    const error = document.createElement('div');
    error.className = 'task-error';
    error.style.fontSize = '11px';
    error.style.color = '#f44';
    error.style.marginTop = '4px';
    error.textContent = '错误: ' + task.error;
    el.appendChild(error);
  }
  
  return el;
}

function updateQueueStats() {
  // 节流优化：避免频繁更新统计信息
  if (queueStatsTimer) {
    clearTimeout(queueStatsTimer);
  }
  
  queueStatsTimer = setTimeout(() => {
    const stats = tasks.reduce((acc, task) => {
      acc.total++;
      if (task.status === 'active') acc.active++;
      if (task.status === 'completed') acc.completed++;
      return acc;
    }, { total: 0, active: 0, completed: 0 });
    
    if (queueStats) {
      queueStats.textContent = `总计: ${stats.total} | 进行中: ${stats.active} | 已完成: ${stats.completed}`;
    }
    queueStatsTimer = null;
  }, STATS_UPDATE_DELAY);
}

async function pauseTask(taskId) {
  await ipcRenderer.invoke('pause-task', taskId);
}

async function resumeTask(taskId) {
  await ipcRenderer.invoke('resume-task', taskId);
}

async function cancelTask(taskId) {
  await ipcRenderer.invoke('cancel-task', taskId);
}

async function retryTask(taskId) {
  await ipcRenderer.invoke('retry-task', taskId);
}

// ==================== 通知管理 ====================

async function loadNotifications() {
  notifications = await ipcRenderer.invoke('get-notifications');
  renderNotifications();
  updateNotificationBadge();
}

function renderNotifications() {
  notificationList.innerHTML = '';
  
  if (notifications.length === 0) {
    notificationList.innerHTML = '<div class="empty-state"><div>暂无通知</div></div>';
    return;
  }
  
  notifications.forEach(notif => {
    const item = createNotificationElement(notif);
    notificationList.appendChild(item);
  });
}

function createNotificationElement(notif) {
  const el = document.createElement('div');
  el.className = 'notification-item' + (notif.isRead ? '' : ' unread');
  el.onclick = () => markNotificationRead(notif.id);
  
  const title = document.createElement('div');
  title.className = 'notification-title';
  title.textContent = notif.title;
  
  const content = document.createElement('div');
  content.className = 'notification-content';
  content.textContent = notif.content;
  
  const time = document.createElement('div');
  time.className = 'notification-time';
  time.textContent = new Date(notif.createdAt).toLocaleString();
  
  el.appendChild(title);
  el.appendChild(content);
  el.appendChild(time);
  
  return el;
}

async function markNotificationRead(notifId) {
  await ipcRenderer.invoke('mark-notification-read', notifId);
  loadNotifications();
}

async function updateNotificationBadge() {
  const count = await ipcRenderer.invoke('get-unread-count');
  if (notificationBadge) {
    notificationBadge.textContent = count;
    notificationBadge.style.display = count > 0 ? 'block' : 'none';
  }
}

// ==================== 传输过滤器 ====================
function filterTasks() {
  renderTransferList();
}

// 加载更多任务
function loadMoreTasks() {
  isLoadingMore = true;
  currentPage++;
  renderTransferList(true); // 追加模式
}

// ==================== IPC事件监听 ====================
ipcRenderer.on('task-added', (event, task) => {
  // 将新任务添加到数组开头（最新的任务）
  tasks.unshift(task);
  
  // 重新渲染列表（重置到第一页，显示最新任务）
  currentPage = 1;
  renderTransferList();
  updateQueueStats();
});

ipcRenderer.on('task-progress', (event, task) => {
  // 性能优化：减少日志输出频率（只在整数百分比变化时输出）
  if (task.progress % 10 === 0 || task.progress === 100) {
    console.log(`📊 进度更新 - 任务 #${task.id}: ${task.fileName} - ${task.progress.toFixed(1)}% (${formatFileSize(task.transferred)}/${formatFileSize(task.fileSize)}) @ ${formatSpeed(task.speed)}`);
  }
  
  const index = tasks.findIndex(t => t.id === task.id);
  if (index !== -1) {
    const oldTask = tasks[index];
    
    // 如果任务从失败状态变为active（重试），立即清除错误并更新UI
    if (task.status === 'active' && oldTask.status === 'failed' && oldTask.error) {
      task.error = null;
      tasks[index] = task;
      // 立即更新DOM，不使用节流
      updateTaskElementDirect(task);
      return;
    }
    
    // 如果任务正在传输（active状态），清除之前的错误信息
    if (task.status === 'active' && tasks[index].error) {
      task.error = null;
    }
    
    tasks[index] = task;
    
    // 使用节流更新DOM，避免频繁重绘
    throttleTaskUpdate(task);
  }
});

ipcRenderer.on('task-completed', (event, task) => {
  const index = tasks.findIndex(t => t.id === task.id);
  if (index !== -1) {
    // 强制清除错误信息（任务已成功完成）
    task.error = null;
    tasks[index] = task;
    updateTaskElement(task);
    updateQueueStats();
    
    // 🔄 任务完成后自动刷新远程目录
    if (task.type === 'upload' && currentRemotePath) {
      console.log('📁 上传任务完成，自动刷新远程目录');
      refreshRemoteDirectory();
    }
  }
});

ipcRenderer.on('task-failed', (event, task) => {
  const index = tasks.findIndex(t => t.id === task.id);
  if (index !== -1) {
    tasks[index] = task;
    updateTaskElement(task);
    updateQueueStats();
  }
});

ipcRenderer.on('task-paused', (event, task) => {
  const index = tasks.findIndex(t => t.id === task.id);
  if (index !== -1) {
    tasks[index] = task;
    updateTaskElement(task);
    updateQueueStats();
  }
});

ipcRenderer.on('task-resumed', (event, task) => {
  const index = tasks.findIndex(t => t.id === task.id);
  if (index !== -1) {
    tasks[index] = task;
    updateTaskElement(task);
    updateQueueStats();
  }
});

ipcRenderer.on('task-cancelled', (event, task) => {
  const index = tasks.findIndex(t => t.id === task.id);
  if (index !== -1) {
    tasks[index] = task;
    updateTaskElement(task);
    updateQueueStats();
  }
});

ipcRenderer.on('notification-received', (event, notif) => {
  loadNotifications();
});

ipcRenderer.on('completed-tasks-cleared', (event, count) => {
  // 从本地任务列表中移除已完成的任务
  tasks = tasks.filter(t => t.status !== 'completed');
  
  // 重新渲染列表
  currentPage = 1; // 重置到第一页
  renderTransferList();
  updateQueueStats();
  
  console.log(`✅ 已清除 ${count} 个已完成的任务`);
});

// 节流更新函数 - 避免频繁更新DOM
function throttleTaskUpdate(task) {
  const taskId = task.id;
  
  // 保存最新的任务数据
  pendingUpdates.set(taskId, task);
  
  // 添加到批量更新队列
  batchUpdateQueue.add(taskId);
  
  // 使用requestAnimationFrame批量更新
  if (!rafId) {
    rafId = requestAnimationFrame(() => {
      // 批量更新所有待更新的任务
      batchUpdateQueue.forEach(id => {
        const latestTask = pendingUpdates.get(id);
        if (latestTask) {
          updateTaskElementDirect(latestTask);
          pendingUpdates.delete(id);
        }
      });
      
      batchUpdateQueue.clear();
      rafId = null;
    });
  }
}

// 直接更新任务元素（不使用节流）
function updateTaskElementDirect(task) {
  const el = document.querySelector(`[data-task-id="${task.id}"]`);
  if (!el) {
    return; // 元素不存在，静默忽略
  }
  
  // 使用will-change提示浏览器优化
  el.style.willChange = 'transform';
  
  // 批量读取DOM属性（避免布局抖动）
  const progressFill = el.querySelector('.progress-fill');
  const taskInfo = el.querySelector('.task-info');
  const currentStatus = el.dataset.status;
  
  // 批量写入DOM（减少重排/重绘）
  if (progressFill) {
    progressFill.style.width = task.progress + '%';
    if (progressFill.className !== `progress-fill ${task.status}`) {
      progressFill.className = `progress-fill ${task.status}`;
    }
  }
  
  if (taskInfo) {
    const spans = taskInfo.querySelectorAll('span');
    if (spans[0]) {
      const newText = `${formatFileSize(task.transferred)} / ${formatFileSize(task.fileSize)}`;
      if (spans[0].textContent !== newText) {
        spans[0].textContent = newText;
      }
    }
    if (spans[1]) {
      const newSpeed = task.speed > 0 ? formatSpeed(task.speed) : '-';
      if (spans[1].textContent !== newSpeed) {
        spans[1].textContent = newSpeed;
      }
    }
    if (spans[2]) {
      const newStatus = getStatusText(task.status);
      if (spans[2].textContent !== newStatus) {
        spans[2].textContent = newStatus;
      }
    }
  }
  
  // 状态变化时更新按钮
  if (currentStatus !== task.status) {
    el.dataset.status = task.status;
    const actions = el.querySelector('.task-actions');
    if (actions) {
      updateTaskActions(actions, task);
    }
  }
  
  // 更新或移除错误信息（只有failed状态才显示错误）
  let errorEl = el.querySelector('.task-error');
  if (task.error && task.status === 'failed') {
    // 显示或更新错误信息
    if (!errorEl) {
      errorEl = document.createElement('div');
      errorEl.className = 'task-error';
      errorEl.style.fontSize = '11px';
      errorEl.style.color = '#f44';
      errorEl.style.marginTop = '4px';
      el.appendChild(errorEl);
    }
    errorEl.textContent = '错误: ' + task.error;
  } else if (errorEl) {
    // 移除错误信息（任务不是failed状态或没有错误）
    errorEl.remove();
  }
  
  // 清除will-change
  setTimeout(() => {
    el.style.willChange = 'auto';
  }, 100);
}

// 更新任务操作按钮
function updateTaskActions(actions, task) {
  actions.innerHTML = '';
  
  if (task.status === 'active') {
    const pauseBtn = document.createElement('button');
    pauseBtn.className = 'task-btn';
    pauseBtn.textContent = '⏸️ 暂停';
    pauseBtn.onclick = () => pauseTask(task.id);
    actions.appendChild(pauseBtn);
  } else if (task.status === 'paused') {
    const resumeBtn = document.createElement('button');
    resumeBtn.className = 'task-btn';
    resumeBtn.textContent = '▶️ 继续';
    resumeBtn.onclick = () => resumeTask(task.id);
    actions.appendChild(resumeBtn);
  } else if (task.status === 'failed') {
    const retryBtn = document.createElement('button');
    retryBtn.className = 'task-btn';
    retryBtn.textContent = '🔄 重试';
    retryBtn.onclick = () => retryTask(task.id);
    actions.appendChild(retryBtn);
  }
  
  if (task.status !== 'completed') {
    const cancelBtn = document.createElement('button');
    cancelBtn.className = 'task-btn';
    cancelBtn.textContent = '✕ 取消';
    cancelBtn.onclick = () => cancelTask(task.id);
    actions.appendChild(cancelBtn);
  }
}

// 非节流的任务更新（用于完成、失败等需要立即更新的场景）
function updateTaskElement(task) {
  const el = document.querySelector(`[data-task-id="${task.id}"]`);
  if (!el) {
    // 任务元素不存在，可能被过滤掉了
    return;
  }
  
  // 调用直接更新函数（已包含错误信息处理）
  updateTaskElementDirect(task);
}

// ==================== 工具函数 ====================
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

function formatSpeed(bytesPerSecond) {
  return formatFileSize(bytesPerSecond) + '/s';
}

function getStatusText(status) {
  const statusMap = {
    pending: '等待中',
    active: '传输中',
    paused: '已暂停',
    completed: '已完成',
    failed: '失败',
    cancelled: '已取消'
  };
  return statusMap[status] || status;
}

// ==================== 初始化 ====================
async function initialize() {
  console.log('[Main] ========== 开始初始化应用 ==========');
  
  // 首先获取所有DOM元素
  console.log('[Main] 1. 获取DOM元素...');
  getDOMElements();
  console.log('[Main] localFiles 元素:', localFiles ? '已找到' : '未找到');
  console.log('[Main] remoteFiles 元素:', remoteFiles ? '已找到' : '未找到');
  
  // 绑定事件监听器
  console.log('[Main] 2. 绑定事件监听器...');
  setupEventListeners();
  
  // 设置用户头像
  try {
    const userData = await ipcRenderer.invoke('get-user-data');
    if (userData && userData.user) {
      const userAvatarImg = document.getElementById('userAvatarImg');
      if (userAvatarImg && userData.user.avatar_url) {
        userAvatarImg.src = userData.user.avatar_url;
        userAvatarImg.onerror = function() {
          // 如果头像加载失败，使用默认头像
          this.src = './assets/avatar.png';
        };
      }
    }
  } catch (error) {
    console.error('设置用户头像失败:', error);
  }
  
  // 更新服务器状态
  await updateServerStatus();
  setInterval(updateServerStatus, 5000);
  
  // 获取默认本地路径（用户主目录）
  console.log('[Main] 3. 获取默认本地路径...');
  if (!currentLocalPath) {
    try {
      currentLocalPath = await ipcRenderer.invoke('get-home-path');
      console.log('[Main] 默认本地路径:', currentLocalPath);
    } catch (error) {
      console.error('[Main] 获取主目录失败:', error);
      currentLocalPath = os.homedir();
    }
  }
  
  // 加载本地文件
  console.log('[Main] 4. 加载本地文件...');
  if (localFiles) {
    await loadLocalDirectory(currentLocalPath);
    console.log('[Main] ✅ 本地文件加载完成');
  } else {
    console.error('[Main] ❌ localFiles 元素未找到，无法加载本地文件');
  }
  
  // 加载远程文件（应用启动时自动加载）
  console.log('[Main] 5. 加载远程文件...');
  if (remoteFiles) {
    await loadRemoteDirectory(currentRemotePath);
    console.log('[Main] ✅ 远程文件加载完成');
  } else {
    console.error('[Main] ❌ remoteFiles 元素未找到，无法加载远程文件');
  }
  
  // 启动远程目录定期刷新（每30秒检查一次）
  setInterval(() => {
    if (currentRemotePath) {
      console.log('[Main] ⏰ 定时刷新远程目录');
      refreshRemoteDirectory();
    }
  }, 30000); // 30秒
  
  // 加载传输任务
  console.log('[Main] 6. 加载传输任务...');
  await loadTasks();
  
  // 加载通知
  console.log('[Main] 7. 加载通知...');
  await loadNotifications();
  
  console.log('[Main] ========== 应用初始化完成 ==========');
}

// 将 initialize 暴露到 window，供新架构调用
window.initialize = initialize;

// 页面加载时初始化（兼容旧架构）
if (document.readyState === 'loading') {
  window.addEventListener('DOMContentLoaded', initialize);
} else {
  // DOM 已经加载完成，直接初始化
  // 在新架构中，这种情况下不自动初始化，等待 base.js 调用
  console.log('[Main] DOM已就绪，等待手动初始化');
}

} // 结束 else 块
